import {Directive, ElementRef, Renderer, HostListener} from '@angular/core';
@Directive({
  selector: '[iotekMoveable]'
})
export class MoveableDirective {
  public position = {
    deltaX: 0,
    deltaY: 0
  };
  private isDownFlag = false;
  constructor(private ele: ElementRef, private render: Renderer) {}

  @HostListener('mousedown', ['$event'])
  public onMouseDown(event) {
    var moveableZone = event.srcElement.getAttribute('moveable-zone');
    if(typeof moveableZone == 'string') {
      this.isDownFlag = true;
      let popoverX: number = this.getPxNumber(this.ele.nativeElement.style.left);
      let popoverY: number = this.getPxNumber(this.ele.nativeElement.style.top);
      this.position.deltaX = event.clientX - popoverX;
      this.position.deltaY = event.clientY - popoverY;
    }
  }
  @HostListener('mousemove', ['$event'])
  public onMouseMove(event){
    if(this.isDownFlag) {
      this.render.setElementStyle(this.ele.nativeElement, 'left', (event.clientX - this.position.deltaX) + 'px');
      this.render.setElementStyle(this.ele.nativeElement, 'top', (event.clientY - this.position.deltaY) + 'px');
      this.render.setElementStyle(this.ele.nativeElement, 'opacity', '0.6');
    }
  }
  @HostListener('mouseup', ['$event'])
  public onMouseUp(event){
    this.isDownFlag = false;
    this.render.setElementStyle(this.ele.nativeElement, 'opacity', '1');
  }
  private getPxNumber(px): number {
    if(!px || px.lastIndexOf('px') == -1) {
      return 0;
    } else {
      return px.match(/[0-9]+/g)[0] * 1
    }
  }
}
